// Author: Bjorn Schobben, Domien Nowicki


#include <assert.h>
#include <QPainter>
#include "SoftRendererWidget.h"



SoftRendererWidget::SoftRendererWidget(QWidget *parent, Qt::WFlags flags): RendererWidget(parent, flags), image(0)
{
	// Create new screen image
	image = new QImage(GetWidth(), GetHeight(), QImage::Format_RGB32);
}

SoftRendererWidget::~SoftRendererWidget()
{
	// Clean up 
	if (0 != image)
	{
		delete image;
		image = 0;
	}
}

void SoftRendererWidget::Update()
{
	update();
}


void SoftRendererWidget::SetPixel(unsigned int x, unsigned int y, const Pixel& pixel)
{
	assert(0 != image);
	assert(x >= 0 && x < image->width());
	assert(y >= 0 && y < image->height());

	image->setPixel(x, y, qRgb(pixel.GetRed(), pixel.GetGreen(), pixel.GetBlue()));
}

Pixel SoftRendererWidget::GetPixel(unsigned int x, unsigned int y) const
{
	assert(0 != image);

	QRgb color = image->pixel(x,y);

	return Pixel(qRed(color), qGreen(color), qBlue(color));
}

unsigned int SoftRendererWidget::GetHeight() const
{
	return height();
}

unsigned int SoftRendererWidget::GetWidth() const
{
	return width();
}

void SoftRendererWidget::resizeEvent(QResizeEvent *e)
{
	if (0 != image)
	{
		delete image;
	}

	// Create new image with new size
	image = new QImage(GetWidth(), GetHeight(), QImage::Format_RGB32);
}

void SoftRendererWidget::paintEvent(QPaintEvent *e)
{
	QPainter painter(this);

	painter.drawImage(QPoint(0, 0), *image);

}

void SoftRendererWidget::DrawPolygon(const Poly& poly)
{
	if (image)
	{
		const Pixel& color = poly.GetColor();

		QColor qColor(color.GetRed(), color.GetGreen(), color.GetBlue(), color.GetAlpha());

		QPainter painter(image);
		painter.setRenderHint(QPainter::Antialiasing);

		// Convert Poly into QPolygon
		QPolygon qPoly(poly.GetSize());

		for(int i=0; i<poly.GetSize(); i++)
		{
			const Vector& vec = poly.GetPoint(i);

			qPoly.setPoint(i, QPoint(vec.GetIntX(), vec.GetIntY()));
		}


		// Set color and draw polygon
		painter.setBrush(qColor);
		painter.setPen(Qt::NoPen);
		painter.drawConvexPolygon(qPoly);
	}
}